<?php
namespace app\index\service;
use think\Validate;
use think\Session;
use app\model\User;
use app\model\Pid;
use app\model\Order;
use app\model\Collect;
use app\model\Goods;
use app\model\OrderLog;
use app\model\Bankcard;
use app\model\Cash;

class MarketService{
    public function pidGet()
    {
        $user_session = Session::get('date');
        if(!$user_session){
            return ['code'=>-1,'msg'=>'请先登录'];
        }
        $userModel = new User;
        $userPids = $userModel::with('pids')->where('id',$user_session['id'])->find();
        // dump($userPids);die;
        $times = strtotime('-7 day');
        return ['code'=>1,'result'=>$userPids,'times'=>$times];
    }

    public function insertPidGet()
    {
        $user_session = Session::get('date');
        if(!$user_session){
            return ['code'=>-1,'msg'=>'请先登录'];
        }
        return ['code'=>1];
    }

    public function insertPidPost($post)
    {
        $user_session = Session::get('date');
        if(!$user_session){
            return ['code'=>-1,'msg'=>'请先登录'];
        }
        $pidModel = new Pid;
        $user_pid = $pidModel::where(['uid'=>$user_session['id'],'pid'=>$post['field']['pid']])->find();
        // dump($pidModel->getLastSql());die;
        if(!empty($user_pid)){
            return ['code'=>-2,'msg'=>'该pid已绑定'];
        }
        $data['pid'] = $post['field']['pid'];
        $data['uid'] = $user_session['id'];
        $pid = explode('_',$post['field']['pid']);
        $data['pid_uid'] = $pid[1];
        $data['pid_pro_id'] = $pid[2];
        $data['pid_ab_id'] = $pid[3];
        $data['add_time'] = time();

        if(array_key_exists('status',$post['field'])){
            $pid_selected = $pidModel::where(['uid'=>$user_session['id'],'status'=>1])->find();
            $data['status'] = 1;
            if(!empty($pid_selected)){
                $info_selected = $pidModel::where('id',$pid_selected['id'])->update(['status'=>2]);
                if(!$info_selected){
                    return ['code'=>-3,'msg'=>'系统繁忙'];
                }
                // $info = $pidModel::insert($data);
            }
            $info = $pidModel::insert($data);
            if(!$info){
                if($info_selected){
                    $pidModel::where('id',$pid_selected['id'])->update(['status'=>1]);
                }
                return ['code'=>-4,'msg'=>'系统繁忙'];
            }
        }else{
            $data['status'] = 2;
            $info = $pidModel::insert($data);
            if(!$info){
                return ['code'=>-3,'msg'=>'系统繁忙'];
            }
        }
        return ['code'=>1,'msg'=>'新增成功'];
    }

    public function editPidGet($id)
    {
        $pidModel = new Pid;
        $pid = $pidModel::get($id);
        return $pid;
    }

    public function editPidPost($post)
    {
        $user_session = Session::get('date');
        if(!$post['pid']){
            return ['code'=>-1,'msg'=>'请填写pid'];
        }
        $id = $post['id'];
        $data['pid'] = $post['pid'];
        $pid = explode('_',$post['pid']);
        $data['pid_uid'] = $pid[1];
        $data['pid_pro_id'] = $pid[2];
        $data['pid_ab_id'] = $pid[3];
        $data['add_time'] = time();
        $pidModel = new Pid;
        if(array_key_exists('status',$post)){
            $pid_selected = $pidModel::where(['uid'=>$user_session['id'],'status'=>1])->find();
            if(!empty($pid_selected) && $pid_selected->id != $id){
                $info_selected = $pidModel::where('id',$pid_selected->id)->update(['status'=>2]);
                if(!$info_selected){
                    return ['code'=>-2,'msg'=>'系统繁忙'];
                }
            }
            $data['status'] = 1;
            $info = $pidModel::where('id',$id)->update($data);
            if(!$info){
                if($info_selected){
                    $pidModel::where('id',$pid_selected->id)->update(['status'=>1]);
                }
                return ['code'=>-3,'msg'=>'系统繁忙'];
            }
        }else{
            $data['status'] = 2;
            $info = $pidModel::where('id',$id)->update($data);
            if(!$info){
                return ['code'=>-2,'msg'=>'系统繁忙'];
            }
        }
        return ['code'=>1,'msg'=>'修改成功'];
    }

    public function sureSession($session_key)
    {
        $user_session = Session::get('date');
        if(!$user_session){
            return ['code'=>-1,'msg'=>'请先登录'];
        }
        $userModel = new User;
        $info = $userModel::where('id',$user_session['id'])->update(['session_key'=>$session_key,'up_session_time'=>time()]);
        if(!$info){
            return ['code'=>-2,'msg'=>'系统繁忙'];
        }
        return ['code'=>1,'msg'=>'更新成功'];
    }

    public function infomationGet()
    {
        $user_session = Session::get('date');
        $userModel = new User;
        $user = $userModel::get($user_session['id'])->toArray();
        if($user['address']){
            $address = explode('-',$user['address']);
            $user['s_province'] = $address[0];
            $user['s_city'] = $address[1];
        }
        if(!$user['sex']){
            $user['sex'] = 0;
        }
        // dump($user);die;
        return $user;
    }

    public function infomationPost($post)
    {
        $rule = [
            'username'  => 'require',
            'sex'       => 'require',
            'age'       => 'number|between:1,120',
        ];
        $msg = [
            'username.require' => '昵称必须',
            'sex.require'      => '性别必须',
            'age.number'       => '年龄必须是数字',
            'age.between'      => '年龄只能在1-120之间',
        ];
        $data = [
            'username'  => $post['username'],
            'sex'       => $post['sex'],
            'age'       => $post['age'],
        ];
        $validate = new Validate($rule);
        if (!$validate->check($data)) {
            return ['code'=>0,'msg'=>$validate->getError()];
        }
        if($post['s_province'] == '省份' || $post['s_city'] == '地级市'){
            return ['code'=>0,'msg'=>'所在地必须'];
        }
        if(!$post['qq'] && !$post['weixin']){
            return ['code'=>0,'msg'=>'QQ和微信最少要填写一项'];
        }
        $data['address'] = $post['s_province'].'-'.$post['s_city'];
        if($post['qq']){
            $data['qq'] = $post['qq'];
        }
        if($post['weixin']){
            $data['weixin'] = $post['weixin'];
        }
        $user = Session::get('date');
        $userModel = new User;
        $info = $userModel::where('id',$user['id'])->update($data);
        if(!$info){
            return ['code'=>-1,'msg'=>'系统繁忙'];
        }
        return ['code'=>1,'msg'=>'保存成功'];
    }

    public function balance($param)
    {
        $user_session = Session::get('date');
        $collectModel = new Collect;
        $collects = $collectModel::where(['uid'=>$user_session['id'],'status'=>1])->column('goods_id');
        // dump($collects);die;
        $str = 'id in ('.implode(',',$collects).')';
        if(array_key_exists('keywords',$param)){
            $str .= " AND (sp_id like '%".$param['keywords']."%' OR title like '%".$param['keywords']."%')";
        }
        // dump($str);die;
        $goodsModel = new Goods;
        $goodses = $goodsModel::with('goodsCate')->where($str)->paginate(3,false,[
            'query' => $param,
            'type'      => 'page\Page',
            'var_page'  => 'page',
        ]);
        // dump($goodsModel->getLastSql());die;
        $page = $goodses->render();
        return ['goodses'=>$goodses,'page'=>$page];
    }

    public function balancePost($post)
    {
        $user_session = Session::get('date');
        $collectModel = new Collect;
        $collects = $collectModel::with([
            'goods' => function($query){
                $query->field('id,sp_id');
            }
        ])->where(['uid'=>$user_session['id'],'status'=>1])->where('goods_id','in',$post['ids'])->select();
        // dump($collects);die;
        $orderModel = new Order;
        $orderLogModel = new OrderLog;
        // $last_month_begin_time = strtotime(date('Y-m-01 00:00:00',strtotime('-1 month')));//上个月的开始时间
        // $this_month_begin_time = mktime(0,0,0,date('m'),1,date('Y'));//这个月的开始时间
        $begin_time = strtotime(date('Y-m-d',strtotime("-20 day")));
        // dump($begin_time);die;
        foreach($collects as $k=>$v){
            $count = $orderModel::where(['uid'=>$user_session['id'],'num_iid'=>$v->goods->sp_id,'tk_status'=>3,'status'=>0])->where('create_time','lt',$begin_time)->count();
            if($count){
                $info = $orderModel::where(['uid'=>$user_session['id'],'num_iid'=>$v->goods->sp_id,'tk_status'=>3,'status'=>0])->where('create_time','lt',$begin_time)->update(['status'=>1]);
            }else{
                $info = 0;
            }
            $order_log = $orderLogModel::where(['uid'=>$user_session['id'],'goods_id'=>$v->goods_id])->find();
            if(!empty($order_log)){
                $counts = $count + (int)$order_log->counts;
                $orderLogModel::where('id',$order_log->id)->update(['add_time'=>time(),'counts'=>$counts]);
            }else{
                $arr['uid'] = $user_session['id'];
                $arr['goods_id'] = $v->goods_id;
                $arr['log_note'] = '订单申请结算';
                $arr['add_time'] = time();
                $arr['counts'] = $count;
                $orderLogModel::insert($arr);
            }
        }
        return true;
    }

    public function balance_xq($param)
    {
        $goodsModel = new Goods;
        $goods = $goodsModel::find($param['goods_id']);
        // dump($goods);die;
        $orderModel = new Order;
        $str = 'num_iid = '.$goods->sp_id.' AND tk_status = 3';
        if(array_key_exists('status',$param)){
            $str .= ' AND status = '.$param['status'];
        }
        $orders = $orderModel::where($str)->order('create_time desc')->paginate(15,false,[
            'query' => $param,
            'type'      => 'page\Page',
            'var_page'  => 'page',
        ]);
        $page = $orders->render();
        return ['goods'=>$goods,'orders'=>$orders,'page'=>$page];
    }

    public function balance_xq_post($post)
    {
        $user_session = Session::get('date');
        $ids = $post['ids'];
        $orderModel = new Order;
        $orders = $orderModel::where('id','in',$ids)->select();
        $have_balance_order = [];//保存不能结算的订单
        foreach($orders as $k=>$v){
            if($v->status != 0 || $v->tk_status != 3){
                $have_balance_order[] = $v->id;
            }
        }
        if(!empty($have_balance_order)){
            return ['code'=>-1,'msg'=>'此订单不能结算','result'=>implode(',',$have_balance_order)];
        }
        $goods_id = $post['goods_id'];
        $info_order = $orderModel::where('id','in',$ids)->update(['status'=>1]);
        if(!$info_order){
            return ['code'=>-2,'msg'=>'系统繁忙'];
        }
        $orderLogModel = new OrderLog;
        $orderLog = $orderLogModel::where(['uid'=>$user_session['id'],'goods_id'=>$goods_id])->find();
        if(empty($orderLog)){
            $arr = [
                'uid'    => $user_session['id'],
                'goods_id' => $goods_id,
                'log_note' => '订单申请结算',
                'counts'   => count(explode(',',$ids)),
                'add_time' => time(),
            ];
            $info_order_log = $orderLogModel::insert($arr);
        }else{
            $counts = count(explode(',',$ids)) + (int)$orderLog->counts;
            $info_order_log = $orderLogModel::where('id',$orderLog->id)->update(['counts'=>$counts,'add_time'=>time()]);
        }
        if(!$info_order_log){
            $orderModel::where('id','in',$ids)->update(['status'=>0]);
            return ['code'=>-3,'msg'=>'系统繁忙'];
        }
        return ['code'=>1,'结算申请已提交'];
    }

    public function hasBindCard($type = 1)//$type是否返回用户银行卡信息：1.不返回，2.返回
    {
        $user_session = Session::get('date');
        $bankcardModel = new Bankcard;
        $user_bankcard = $bankcardModel::where('uid',$user_session['id'])->find();
        if(empty($user_bankcard)){
            return false;
        }else{
            if($type == 1){
                return true;
            }else{
                return $user_bankcard;
            }
        }
    }

    public function userInfomation()
    {
        $user_session = Session::get('date');
        $userModel = new User;
        return $userModel::find($user_session['id']);
    }

    public function cashPost($account)
    {
        $user_session = Session::get('date');
        $userModel = new User;
        $user = $userModel::with('userBankcard')->find($user_session['id']);
        if($account > $user->balance || $account <=0){
            return ['code'=>-1,'msg'=>'请填写正确的提现金额'];
        }
        $cashModel = new Cash;
        $info_cash = $cashModel::insert([
            'uid'    => $user->id,
            'bankcard_id'  => $user->user_bankcard->id,
            'account'   => $account,
            'add_time'  => time()
        ]);
        if(!$info_cash){
            return ['code'=>-2,'msg'=>'系统繁忙'];
        }
        $arr = [
            'balance' => $user->balance - $account,
            // 'cash'    => $user->cash + $account,
        ];
        $info_user = $userModel::where('id',$user->id)->update($arr);
        if(!$info_user){
            $cashModel::where('id',$info_cash)->delete();
            return ['code'=>-3,'msg'=>'系统繁忙'];
        }
        return ['code'=>1,'msg'=>'提现申请已提交'];
    }
}
